package core

import (
	"crypto/sha256"
	"encoding/hex"
	"time"
)

//定义区块
type Block struct {
	Index         int64  //区块编号
	Timestamp     int64  //区块链时间戳
	PrevBlockHash string //上一个区块哈希值
	Hash          string //当前区块哈希值

	Data string //区块数据
}

//计算哈希值
func calculateHash(b Block) string {
	//简单将区块的编号、时间戳、父区块哈希值及当前区块的数据进行拼接
	blockData := string(b.Index) + string(b.Timestamp) + b.PrevBlockHash + b.Data
	//进行哈希运算
	hashInBytes := sha256.Sum256([]byte(blockData))
	hashInStr := hex.EncodeToString(hashInBytes[:])
	//log.Printf("blockData = %s , hashInStr = %s", blockData, hashInStr)
	return hashInStr
}

//生成区块（传入父区块，新区块的数据体）
func GenerateNewBlock(preBlock Block, data string) Block {
	newBlock := Block{}
	//区块编号自增
	newBlock.Index = preBlock.Index + 1
	newBlock.PrevBlockHash = preBlock.Hash
	newBlock.Timestamp = time.Now().Unix()
	newBlock.Data = data
	//计算哈希值
	newBlock.Hash = calculateHash(newBlock)
	return newBlock
}

//生成创世区块
func GenerateGenesisBlock() Block {
	preBlock := Block{}
	//创世区块索引一般为0
	preBlock.Index = -1
	//创世区块没有父区块，所以他的父区块哈希值设置为空字符串即可
	preBlock.Hash = ""
	//复用生成区块函数，生成创世区块
	return GenerateNewBlock(preBlock, "Genesis Block")
}
